//
//  GKZYPostBarHomePageViewController.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/14.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYPostBarHomePageViewController.h"

@interface GKZYPostBarHomePageViewController ()

@end

@implementation GKZYPostBarHomePageViewController

//加载数据
- (void)viewDidAppear:(BOOL)animated
{
    NSError *error;
    self.arrayCommentCount = [[NSMutableArray alloc] init];
    self.arrayPublicationID = [[NSMutableArray alloc] init];
    self.arrayPublish = [[NSMutableArray alloc] init];
    AVQuery *queryPostBar = [PostBar query];
    [queryPostBar orderByDescending:@"createdAt"];
    [queryPostBar includeKey:@"arrayPublicationImage"];
    [queryPostBar includeKey:@"strPublicationUserName"];
    if (self.arrayAllData) {
        self.arrayAllData = nil;
    }
    [self addActivityIndicatorView];
    self.arrayAllData = [queryPostBar findObjects:&error].mutableCopy;
    if (!error) {
        [self removeActivityIndicatorView];
        for (PostBar *postBar in self.arrayAllData) {
            if (postBar.strPublicationUserName) {
                [self.arrayPublish addObject:postBar];
                [self.arrayPublicationID addObject:postBar.strPublicationID];
            }
        }
        for (int i = 0; i < self.arrayPublicationID.count; i++) {
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int j = 0; j < self.arrayAllData.count; j++) {
                if ([self.arrayAllData[j][@"strPublicationID"]isEqualToString:self.arrayPublicationID[i]]) {
                    [array addObject:self.arrayAllData[j][@"strPublicationID"]];
                }
            }
            [self.arrayCommentCount addObject:array];
        }
        
        if (self.arrayUserLike.count) {
            [self.arrayUserLike removeAllObjects];
        }
        for (PostBar *bar in self.arrayPublish) {
            if (bar.arrayUserLike) {
                [self.arrayUserLike addObject:bar.arrayUserLike];
            }
        }
        [self.tableViewList reloadData];
    }else{
        [self addDataUploadWrongErrorView];
    }
}

- (NSMutableArray *)arrayAllData
{
    if (!_arrayAllData) {
        _arrayAllData = [[NSMutableArray alloc] init];
    }
    return _arrayAllData;
}

- (NSMutableArray *)arrayUserLike
{
    if (!_arrayUserLike) {
        _arrayUserLike = [[NSMutableArray alloc] init];
    }
    return _arrayUserLike;
}

//加载视图
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"贴吧";
    
    self.tableViewList = [[UITableView alloc] initWithFrame:[UIScreen  mainScreen].bounds style:(UITableViewStyleGrouped)];
    self.tableViewList.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableViewList];
    self.tableViewList.delegate = self;
    self.tableViewList.dataSource = self;
    
    self.rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"发表" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightBarButtonAction:)];
    self.navigationItem.rightBarButtonItem = self.rightBarButton;
}

//发表按钮事件
- (void)rightBarButtonAction:(UIBarButtonItem *)sender
{
    //如果用户已登录,跳转到登录界面
    if ([AVUser currentUser].username) {
        GKZYPostBarPublishViewController *publishVC = [[GKZYPostBarPublishViewController alloc] init];
        [self.navigationController pushViewController:publishVC animated:YES];
    }else{
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayPublish.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PostBar *postBar = self.arrayPublish[indexPath.row];
    
    //有图片cell
    if (postBar.arrayPublicationImage.count) {
        static NSString *publicationCell = @"cell_Publication";
        GKZYPostBarPublicationTableViewCell *cellPublication = [tableView dequeueReusableCellWithIdentifier:publicationCell];
        if (!cellPublication) {
            cellPublication = [[GKZYPostBarPublicationTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:publicationCell];
        }
        [self changeCellFarmeAndContentOnCell:cellPublication byModel:postBar withIndex:indexPath.row];
        return cellPublication;
    }else if(!postBar.arrayPublicationImage.count){     //无图片cell
        static NSString *publicationWithoutImageCell = @"cell_PublicationWithoutImage";
        GKZYPostBarPublicationWithoutImageTableViewCell *cellPublicationWithoutImage = [tableView dequeueReusableCellWithIdentifier:publicationWithoutImageCell];
        if (!cellPublicationWithoutImage) {
            cellPublicationWithoutImage = [[GKZYPostBarPublicationWithoutImageTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:publicationWithoutImageCell];
        }
        [self changeCellFarmeAndContentOnPublicationCellWithoutImage:cellPublicationWithoutImage byModel:postBar withIndex:indexPath.row];
        return cellPublicationWithoutImage;
    }
    
    return nil;
}

//为有图片cell设置cell高度并赋值
- (void)changeCellFarmeAndContentOnCell:(GKZYPostBarPublicationTableViewCell *)cellPublication byModel:(PostBar *)postBar withIndex:(NSInteger)index;
{
    cellPublication.likeView.labelLikeCount.text = @"0";    //设置初值
    [cellPublication.likeView.buttonLike setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
    if (self.arrayUserLike) {
        for (NSString *strUserName in self.arrayUserLike[index]) {
            if ([strUserName isEqualToString:[AVUser currentUser].username]) {
                [cellPublication.likeView.buttonLike setImage:[UIImage imageNamed:@"isliked"] forState:(UIControlStateNormal)];
            }
        }
        cellPublication.likeView.labelLikeCount.text = [NSString stringWithFormat:@"%ld",(unsigned long)((NSMutableArray *)self.arrayUserLike[index]).count];
    }
    NSInteger count = ((NSMutableArray *)self.arrayCommentCount[index]).count - 1;
    cellPublication.labelUserName.text = postBar.strPublicationUserName;
    cellPublication.labelContent.text = postBar.strPublicationrContent;
    cellPublication.likeView.labelCommentCount.text = [NSString stringWithFormat:@"%ld",(long)count];
    
    [self getUserIconByUserName:postBar.strPublicationUserName andAssignmentOnCell:cellPublication];
    
    //返回label高度
    CGRect rectLabelContent = cellPublication.labelContent.frame;
    rectLabelContent.size.height = [cellPublication labelHeight:postBar.strPublicationrContent withFont:17.0f] + 30;
    cellPublication.labelContent.frame = rectLabelContent;
    
    //返回cell高度
    CGRect rectCell = cellPublication.frame;
    rectCell.size.height = cellPublication.labelContent.frame.size.height + self.view.frame.size.width * 0.55 + [cellPublication viewImageHeight];
    cellPublication.frame = rectCell;
    self.cellHeight = cellPublication.frame.size.height;
    
    //置空imageView
    cellPublication.imageView1.image = nil;
    cellPublication.imageView2.image = nil;
    cellPublication.imageView3.image = nil;
    
    //imageView赋值
    if (postBar.arrayPublicationImage.count) {
        if (postBar.arrayPublicationImage.count == 2) {
            AVFile *fileImage = postBar.arrayPublicationImage[0];
            [cellPublication.imageView1 sd_setImageWithURL:[NSURL URLWithString:fileImage.url]];
        }else if (postBar.arrayPublicationImage.count == 3){
            AVFile *fileImage1 = postBar.arrayPublicationImage[0];
            [cellPublication.imageView1 sd_setImageWithURL:[NSURL URLWithString:fileImage1.url]];
            AVFile *fileImage2 = postBar.arrayPublicationImage[1];
            [cellPublication.imageView2 sd_setImageWithURL:[NSURL URLWithString:fileImage2.url]];
        }else if (postBar.arrayPublicationImage.count >= 4){
            AVFile *fileImage1 = postBar.arrayPublicationImage[0];
            [cellPublication.imageView1 sd_setImageWithURL:[NSURL URLWithString:fileImage1.url]];
            AVFile *fileImage2 = postBar.arrayPublicationImage[1];
            [cellPublication.imageView2 sd_setImageWithURL:[NSURL URLWithString:fileImage2.url]];
            AVFile *fileImage3 = postBar.arrayPublicationImage[2];
            [cellPublication.imageView3 sd_setImageWithURL:[NSURL URLWithString:fileImage3.url]];
        }
    }else{
        cellPublication.imageView1.image = nil;
        cellPublication.imageView2.image = nil;
        cellPublication.imageView3.image = nil;
    }
    [cellPublication.likeView.buttonLike addTarget:self action:@selector(buttonLikeAciton:) forControlEvents:(UIControlEventTouchUpInside)];
}

//为无图片cell设置cell高度并赋值
- (void)changeCellFarmeAndContentOnPublicationCellWithoutImage:(GKZYPostBarPublicationWithoutImageTableViewCell *)cellPublication byModel:(PostBar *)postBar withIndex:(NSInteger)index
{
    cellPublication.likeView.labelLikeCount.text = @"0";    //设置初值
    [cellPublication.likeView.buttonLike setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
    if (self.arrayUserLike) {
        for (NSString *strUserName in self.arrayUserLike[index]) {
            if ([strUserName isEqualToString:[AVUser currentUser].username]) {
                [cellPublication.likeView.buttonLike setImage:[UIImage imageNamed:@"isliked"] forState:(UIControlStateNormal)];
            }
        }
        cellPublication.likeView.labelLikeCount.text = [NSString stringWithFormat:@"%ld",(unsigned long)((NSMutableArray *)self.arrayUserLike[index]).count];
    }
    NSInteger count = ((NSMutableArray *)self.arrayCommentCount[index]).count - 1;
    cellPublication.labelUserName.text = postBar.strPublicationUserName;
    cellPublication.labelContent.text = postBar.strPublicationrContent;
    cellPublication.likeView.labelCommentCount.text = [NSString stringWithFormat:@"%ld",(long)count];
    
    [self getUserIconByUserName:postBar.strPublicationUserName andAssignmentOnCellWithoutImage:cellPublication];
    
    //改变cell高度
    CGRect rectLabelContent = cellPublication.labelContent.frame;
    rectLabelContent.size.height = [cellPublication labelHeight:postBar.strPublicationrContent withFont:17.0f] + 30;
    cellPublication.labelContent.frame = rectLabelContent;
    
    CGRect rectCell = cellPublication.frame;
    rectCell.size.height = cellPublication.labelContent.frame.size.height + self.view.frame.size.width * 0.55;
    cellPublication.frame = rectCell;
    self.cellHeight = cellPublication.frame.size.height;
    [cellPublication.likeView.buttonLike addTarget:self action:@selector(buttonLikeAciton:) forControlEvents:(UIControlEventTouchUpInside)];
}

//点赞按钮
- (void)buttonLikeAciton:(UIButton *)sender
{
    if ([AVUser currentUser].username) {
        LikeView *likeView = (LikeView *)[sender superview];
        UITableViewCell *cell = (UITableViewCell *)[likeView superview];
        NSIndexPath *indexPath = [self.tableViewList indexPathForCell:cell];
        NSString *strPublicationID = self.arrayPublish[indexPath.row][@"strPublicationID"];
        NSString *strPublicationUserName = self.arrayPublish[indexPath.row][@"strPublicationUserName"];
        
        AVQuery *query = [PostBar query];
        [query whereKey:@"strPublicationID" equalTo:strPublicationID];
        [query whereKey:@"strPublicationUserName" equalTo:strPublicationUserName];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            PostBar *postBar = objects.firstObject;
            for (NSString *user in postBar.arrayUserLike) {
                if ([user isEqualToString:[AVUser currentUser].username]) {
                    [sender setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
                    [(NSMutableArray *)self.arrayUserLike[indexPath.row] removeObject:user];
                    [postBar setObject:self.arrayUserLike[indexPath.row] forKey:@"arrayUserLike"];
                    [postBar saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            [self.tableViewList reloadData];
                        }else{
                            NSLog(@"%@",error);
                        }
                    }];
                    return ;
                }
            }
            
            [sender setImage:[UIImage imageNamed:@"isliked"] forState:(UIControlStateNormal)];
            [(NSMutableArray *)self.arrayUserLike[indexPath.row] addObject:[AVUser currentUser].username];
            [postBar setObject:self.arrayUserLike[indexPath.row] forKey:@"arrayUserLike"];
            [postBar saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [self.tableViewList reloadData];
                }else{
                    NSLog(@"%@",error);
                }
            }];
        }];
    }else{
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

//获取用户头像
- (void)getUserIconByUserName:(NSString *)userName andAssignmentOnCell:(GKZYPostBarPublicationTableViewCell *)cellPublication
{
    AVQuery *query = [AVQuery queryWithClassName:@"UserInformation"];
    [query whereKey:@"userName" equalTo:userName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        AVFile *fileImage = objects.firstObject[@"userImage"];
        [cellPublication.imageUserHeader sd_setImageWithURL:[NSURL URLWithString:fileImage.url]];
    }];
}

//获取用户名
- (void)getUserIconByUserName:(NSString *)userName andAssignmentOnCellWithoutImage:(GKZYPostBarPublicationWithoutImageTableViewCell *)cellPublication
{
    AVQuery *query = [AVQuery queryWithClassName:@"UserInformation"];
    [query whereKey:@"userName" equalTo:userName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        AVFile *fileImage = objects.firstObject[@"userImage"];
        [cellPublication.imageUserHeader sd_setImageWithURL:[NSURL URLWithString:fileImage.url]];
    }];
}

//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GKZYPostBarDetailsViewController *postBarDeatils = [[GKZYPostBarDetailsViewController alloc] init];
    postBarDeatils.postBar = self.arrayPublish[indexPath.row];
    postBarDeatils.strPublicationID = self.arrayPublicationID[indexPath.row];
    [self.navigationController pushViewController:postBarDeatils animated:YES];
}

//添加活动指示器
- (void)addActivityIndicatorView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [view setTag:108];
    [view setBackgroundColor:[UIColor darkGrayColor]];
    [view setAlpha:0.5];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [self.activityIndicator setCenter:view.center];
    [self.activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    [self.view addSubview:view];
}

//移除活动指示器
- (void)removeActivityIndicatorView
{
    [self.activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
}

//弹框
- (void)addDataUploadWrongErrorView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = [UIColor lightGrayColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height *0.4, self.view.frame.size.width, self.view.frame.size.height * 0.2)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"页面加载出错...";
    [view addSubview:label];
    [self.view addSubview:view];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
